import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: []
  },
  getters: {
    cartItems: state => state.cart,
    totalPrice: state => {
      return state.cart.reduce((total, item) => total + (item.price * item.quantity), 0)
    }
  },
  mutations: {
    ADD_TO_CART(state, product) {
      const existingItem = state.cart.find(item => item.id === product.id);
      if (existingItem) {
        existingItem.quantity += 1;
      } else {
        state.cart.push({ ...product, quantity: 1 });
      }
    },
    REMOVE_FROM_CART(state, productId) {
      state.cart = state.cart.filter(item => item.id !== productId);
    },
    INCREMENT_QUANTITY(state, productId) {
      const item = state.cart.find(item => item.id === productId);
      if (item) {
        item.quantity += 1;
      }
    },
    DECREMENT_QUANTITY(state, productId) {
      const item = state.cart.find(item => item.id === productId);
      if (item && item.quantity > 1) {
        item.quantity -= 1;
      }
    }
  },
  actions: {
    addToCart({ commit }, product) {
      commit('ADD_TO_CART', product);
    },
    removeFromCart({ commit }, productId) {
      commit('REMOVE_FROM_CART', productId);
    },
    incrementQuantity({ commit }, productId) {
      commit('INCREMENT_QUANTITY', productId);
    },
    decrementQuantity({ commit }, productId) {
      commit('DECREMENT_QUANTITY', productId);
    }
  }
})